﻿#region 命名空间

using System;
using System.IO;
using System.Web;
using WinnerCMS.Common;

#endregion

namespace WinnerCMS.WebUI.Scripts.Uploadify
{
    /// <summary>
    ///     UploadHandler 的摘要说明
    /// </summary>
    public class UploadHandler : IHttpHandler
    {
        private const int FileMaxSize = 10240; //文件大小，单位为Kpublicvoid ProcessRequest(HttpContext context)

        public void ProcessRequest(HttpContext context)
        {
            var fileUpload = context.Request.Files[0];
            if (fileUpload != null)
            {
                try
                {
                    const string uploadDir = "~/UpLoadFolder/"; //图片保存的文件夹
                    //图片保存的文件夹路径
                    var path = context.Server.MapPath(uploadDir);
                    //每天上传的图片一个文件夹
                    var folder = DateTime.Now.ToString("yyyyMM");
                    //如果文件夹不存在，则创建
                    if (!Directory.Exists(path + folder))
                    {
                        Directory.CreateDirectory(path + folder);
                    }
                    //上传图片的扩展名
                    var fileExtension = fileUpload.FileName.Substring(fileUpload.FileName.LastIndexOf('.'));
                    //判断文件格式
                    if (!CheckValidExt(fileExtension))
                    {
                        context.Response.Write("错误提示：文件格式不正确！" + fileExtension);
                        return;
                    }
                    //判断文件大小
                    if (fileUpload.ContentLength > FileMaxSize*1024)
                    {
                        context.Response.Write("错误提示：上传的文件(" + fileUpload.FileName + ")超过最大限制：" + FileMaxSize + "KB");
                        return;
                    }
                    //保存图片的文件名
                    var saveName = Guid.NewGuid() + fileExtension;

                    //保存图片
                    var filePath = path + folder + "/" + saveName;
                    fileUpload.SaveAs(filePath);


                    var T = new Thumbnails(filePath);
                    string str = null;
                    var fi = new FileInfo(filePath);

                    var strDateTime = DateTime.Now.ToString("yyMMddhhmmssfff"); //取得时间字符串
                    var ran = new Random();
                    var strRan = Convert.ToString(ran.Next(100, 999)); //生成三位随机数
                    saveName = strDateTime + strRan + fileExtension;

                    var newFilePath = path + folder + "/" + saveName;

                    if (Convert.ToBoolean(context.Request["BiLi"]))
                    {
                        T.ReducedImage(int.Parse(context.Request["PicW"]), int.Parse(context.Request["PicH"]),
                            newFilePath, ref str);
                    }
                    else
                    {
                        T.ReducedImage(int.Parse(context.Request["PicW"]), int.Parse(context.Request["PicH"]),
                            newFilePath);
                    }


                    context.Response.Write(uploadDir.Replace("~/", "/") + folder + "/" + saveName);
                }
                catch
                {
                    context.Response.Write("错误提示：上传失败");
                }
            }
        }

        #region 检测扩展名的有效性 bool CheckValidExt(string sExt)

        /// <summary>
        ///     检测扩展名的有效性
        /// </summary>
        /// <param name="strExt">文件名扩展名</param>
        /// <returns>如果扩展名有效,返回true,否则返回false.</returns>
        public bool CheckValidExt(string strExt)
        {
            var flag = false;
            var arrExt = this.AllowExt.Split('|');
            foreach (var filetype in arrExt)
            {
                if (filetype.ToLower() == strExt.ToLower().Replace(".", ""))
                {
                    flag = true;
                    break;
                }
            }
            return flag;
        }

        #endregion

        protected string AllowExt =
            "7z|aiff|asf|avi|bmp|csv|doc|docx|fla|flv|gif|gz|gzip|jpeg|jpg|mid|mov|mp3|mp4|mpc|mpeg|mpg|ods|odt|pdf|png|ppt|pptx|pxd|qt|ram|rar|rm|rmi|rmvb|rtf|sdc|sitd|swf|sxc|sxw|tar|tgz|tif|tiff|txt|vsd|wav|wma|wmv|xls|xlsx|xml|zip";
            //支持的文件格式

        public bool IsReusable
        {
            get { return false; }
        }
    }
}